<!-- 借鉴自https://blog.csdn.net/weixin_46015333/article/details/127035370 -->
<template>
  <div class="comment">
    <div class="comment-header">
      <el-tooltip class="item" effect="dark" :content="this.userInfo.nickname" placement="top-start">
        <div>
          <input type="file" style="display: none" @change="dealWithdAvatar" ref="avatar" />
          <el-avatar
              :src="userInfo.imageUrl"
              :size="40"
          ></el-avatar>
        </div>
      </el-tooltip>
      <el-input
          :placeholder="placeholderText"
          v-model="context"
          class="input"
          type="textarea"
          resize="none"
          size="mini"
          :maxlength="contentLength"
          @focus="isShowSecReply(undefined)"
      ></el-input>
      <el-button
          type="info"
          style="height: 40px"
          @click="addComment(this.entityId, 1, null, null, this.context)"
      >{{ buttonText }}</el-button>
    </div>
    <div class="comment-body" v-for="(item, index) in comments" :key="item.id + '' + index">
      <!-- 一级评论 -->
      <div class="first-comment">
        <el-avatar :size="40" :src="item.userImageUrl"></el-avatar>
        <div class="content">
          <!-- 一级评论用户昵称 -->
          <h3>{{ item.userNickname }}</h3>
          <!-- 一级评论发布时间 -->
          <span>{{ item.createTime }}</span>
          <!-- 一级评论评论内容 -->
          <p>{{ item.content }}</p>
          <!-- 一级评论评论点赞 -->
          <div class="comment-right">
            <i
                class="el-icon-chat-dot-round"
                @click="isShowSecReply(item.id)"
            >回复</i>
          </div>
          <!-- 回复一级评论 -->
          <div class="reply-comment" v-show="isShowSec === item.id">
            <el-input
                :placeholder="placeholderText"
                class="input"
                v-model.trim="replyContext"
                :maxlength="contentLength"
            ></el-input>
            <el-button
                type="info"
                size="mini"
                class="reply-button"
                @click="addComment(this.entityId, 2, item.id, item.userId, this.replyContext)"
            >回复</el-button>
          </div>
          <!-- 次级评论 -->
          <div
              class="second-comment"
              v-for="(reply, index) in item.children"
              :key="reply.id + '' + index"
          >
            <!-- 次级评论头像,该用户没有头像则显示默认头像 -->
            <el-avatar :size="40" :src="reply.userImageUrl"></el-avatar>
            <div class="content">
              <!-- 次级评论用户昵称 -->
              <h3>{{ reply.userNickname }}</h3>
              <!-- 次级评论评论时间 -->
              <span>{{ reply.createTime }}</span>
              <span class="to_reply">{{ reply.userNickname }}</span>
              回复
              <span class="to_reply">{{ reply.replierNickname }}</span>:
              <p>{{ reply.content }}</p>
              <!-- 次级评论评论点赞 -->
              <div class="comment-right">
                <i
                    class="el-icon-chat-dot-round"
                    @click="isShowSecReply(reply.id)"
                >回复</i>
              </div>
              <div class="reply-comment" v-show="isShowSec === reply.id">
                <el-input
                    :placeholder="placeholderText"
                    class="input"
                    v-model.trim="replyContext"
                    :maxlength="contentLength"
                ></el-input>
                <el-button
                    type="info"
                    size="mini"
                    class="reply-button"
                    @click="addComment(this.entityId, 2, item.id, item.userId, this.replyContext)"
                >回复</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 暂无评论的空状态 -->
    <el-empty :description="emptyText" v-show="comments.length === 0"></el-empty>
  </div>
</template>
<script>
import {getUserInfo} from "@/manager/UserManager"
import axios from "@/settings/axios";
import {successedOutVOHandle} from "@/utils/CommonUtils";

export default {
  props: {
    articleId: {
      //评论所属文章 id
      type: String
    },
    emptyText: {
      // 评论为空的时候显示的文字
      type: String,
      default: "期待你的评论！"
    },
    buttonText: {
      // 按钮文字
      type: String,
      default: "评论"
    },
    contentLength: {
      // 评论长度
      type: Number,
      default: 150
    },
    placeholderText: {
      // 默认显示文字
      type: String,
      default: "请输入最多150字的评论..."
    },
    entityType: {
      type: String,
      default: "",
    },
    entityId: {
      type: String,
      default: "",
    },
  },
  computed: {
  },
  watch: {

    props_loaded: {
      deep: true,
      immediate: true,
      handler: async function (newValue, oldValue) {
        // 监听，一旦里面的元素都有值了，那就请求数据
        oldValue;

        for (let key in newValue) {
          // 一旦为空则跳出函数
          if (newValue[key] === null && newValue[key] === "" && newValue[key] === undefined) {
            return;
          }
        }


        this.getCommentTree()
      }
    }

  },

  data() {
    return {
      comments: [], // 评论列表
      context: "", // 评论内容
      replyContext: "", //一级评论回复
      isShowSec: "", //是否显示次级回复框
      isClickId: "", //记录点击回复的评论id
      firstIdx: 1,
      secIdx: 1,
      avatarUrl:
          "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
      userInfo:{},
      urlGetDict:{
        "answer": "/shane_answer/get_all_comment_by_answer_id",
        "question": "/shane_question/get_all_comment_by_question_id",
        "essay": "/shane_essay/get_all_comment_by_essay_id",
      },
      urlInsertDict:{
        "answer": "/shane_answer/insert_one_comment",
        "question": "/shane_question/insert_one_comment",
        "essay": "/shane_essay/insert_one_comment",
      },
      idKeyDict: {
        "answer": "answerId",
        "question": "questionId",
        "essay": "essayId",
      },
      props_loaded: {
        entityType: this.entityType,
        entityId: this.entityId,
      },

    };
  },
  created() {
    // 获取评论数据
    // this.getCommentList();
  },
  methods: {
    // 唤起文件选择
    handleClick() {
      this.$refs.avatar.click();
    },
    dealWithdAvatar(e) {
      // const maxSize = 2 * 1024 * 1024;
      const file = Array.prototype.slice.call(e.target.files)[0];
      console.log(file);
    },
    // 评论点赞
    // eslint-disable-next-line no-unused-vars
    giveALike(item, _id) {
      try {
        // 不允许同一个人重复点赞
        if (item.favour?.includes(this.userId)) {
          this.$message.info("您已经点过赞啦！");
          return;
        }
        //判断是给一级评论点赞还是二级评论，只有二级评论会有replyName
        if (item.replyName) {
          // 给二级评论点赞，向后台提交数据
        } else {
          // 一级评论点赞，向后台提交数据
        }
        item.favour.push(this.userId);
      } catch (err) {
        this.$message.error(err);
      }
    },
    isShowSecReply(id) {
      if (id) {
        this.isShowSec = id;
        if (this.isClickId === this.isShowSec) {
          this.isShowSec = "";
        } else {
          this.isShowSec = id;
        }
        this.isClickId = this.isShowSec;
      } else {
        this.isShowSec = this.isClickId = "";
      }
      console.log(this.isShowSec)
    },
    async addComment(entityId, commentLevel, parentId, replierUserId, content) {
      let shaneComment = {
        "commentLevel": commentLevel,
        "content": content,
        "parentId": parentId,
        "replierUserId": replierUserId,
        "userId": this.userInfo.userId,
      };
      shaneComment[this.idKeyDict[this.entityType]] = entityId
      let successOutVO = await axios.post(this.urlInsertDict[this.entityType], shaneComment);
      successedOutVOHandle(successOutVO);
      await this.getCommentTree();
      // 评论内容置空
      this.context = "";
      this.replyContext = "";
    },
    async getCommentTree() {
      let params = {};
      params[this.idKeyDict[this.entityType]] = this.entityId;
      let commentTreeListVO = await axios.get(this.urlGetDict[this.entityType], params);
      this.comments = commentTreeListVO;
    },
  },
  async mounted() {
    let userInfo = await getUserInfo();
    this.userInfo = userInfo;
  }
};
</script>

<style lang="less" scoped>
.comment {
  min-height: 26vh;
  border-radius: 5px;
  margin-top: 2px;
  overflow: hidden;
  .active {
    color: rgb(202, 4, 4);
  }
  .comment-header {
    position: relative;
    height: 50px;
    padding: 10px 5px;
    display: flex;
    align-items: center;

    .input {
      margin-left: 10px;
      margin-right: 20px;
      flex: 1;
      /deep/.el-input__inner:focus {
        border-color: #dcdfe6;
      }
    }
  }

  .comment-body {
    min-height: 70px;
    padding: 10px 20px;
    font-size: 14px;
    .first-comment {
      display: flex;
      .input {
        /deep/.el-input__inner:focus {
          border-color: #dcdfe6;
        }
      }
      i {
        margin-right: 5px;
        margin-left: 1vw;
        cursor: pointer;

        &:nth-child(3) {
          color: rgb(202, 4, 4);
        }
      }

      .content {
        margin-left: 10px;
        position: relative;
        flex: 1;

        & > span {
          font-size: 12px;
          color: rgb(130, 129, 129);
        }

        .comment-right {
          position: absolute;
          right: 0;
          top: 0;
        }

        .reply-comment {
          height: 60px;
          display: flex;
          align-items: center;

          .reply-button {
            margin-left: 20px;
            height: 35px;
          }
        }

        .second-comment {
          display: flex;
          padding: 10px 0 10px 5px;
          border-radius: 20px;
          background: #ffffff;
          .to_reply {
            color: rgb(126, 127, 128);
          }
        }
      }
    }
  }
}
</style>
